#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <math.h>
#include <pthread.h>

#include "dbfunc.h"

#define MODULE_NAME "THREAD"

#define	THREAD_QT		3	

typedef void *(*PTHREAD_FUNC)(void *arg);

typedef struct
{
    pthread_t thread_id;
    int thread_index;
    pthread_mutex_t *p_thread_mutex;
    char name[20];
} thread_ctl_t;
static thread_ctl_t a_thread_ctl[THREAD_QT+10];
static char connect[20]="dbuser/oracle";

void *ThreadFunc(thread_ctl_t *p_thread_ctl);


int main()
{
    int index;

    if(DbsEnableThread()!=DB_OK)
    {
        printf("DbsEnableThread fail\n");
        exit(1);
    }

    for(index=0; index<THREAD_QT; index++)
    {
        a_thread_ctl[index].thread_index=index;
        if(pthread_create(&a_thread_ctl[index].thread_id, NULL,
               (void *)ThreadFunc, &a_thread_ctl[index]))
        {
            printf("Thread create fail\n");
            exit(1);
        }
    }
    for(index=0; index<THREAD_QT; index++)
    {
        pthread_join(a_thread_ctl[index].thread_id, NULL);
    }

    exit(0);
}
                         

void *ThreadFunc(thread_ctl_t *p_thread_ctl)
{
    int result;
    emp_t emp;

    if((result=DbsConnectThread(p_thread_ctl->thread_index, connect))!=
       DB_OK)
    {
        printf("Thread:%d connect fail, sqlcode:%d\n",
            p_thread_ctl->thread_index, result); 
        goto THREAD_FUNC_END;
    }

    emp.no=p_thread_ctl->thread_index;
    result=DbsEMP_UPD_Info(p_thread_ctl->thread_index, &emp);
    if(result!=DB_OK && result!=DB_NOTFOUND)
    {
        printf("Thread:%d database error, sqlcode:%d\n",
            p_thread_ctl->thread_index, result); 
        DbsRollback(p_thread_ctl->thread_index);
        goto THREAD_FUNC_END;
    }
    if(result==DB_NOTFOUND)
    {
        printf("Thread:%d not found\n",
            p_thread_ctl->thread_index); 
        DbsRollback(p_thread_ctl->thread_index);
        goto THREAD_FUNC_END;
    }
    DbsCommit(p_thread_ctl->thread_index);

    emp.no=p_thread_ctl->thread_index;
    result=DbsEMP_SEL_Info(p_thread_ctl->thread_index, &emp);
    if(result!=DB_OK && result!=DB_NOTFOUND)
    {
        printf("Thread:%d database error, sqlcode:%d\n",
            p_thread_ctl->thread_index, result); 
        goto THREAD_FUNC_END;
    }
    if(result==DB_NOTFOUND)
    {
        printf("Thread:%d not found\n",
            p_thread_ctl->thread_index); 
        goto THREAD_FUNC_END;
    }
    printf("Thread:%d name:%s, update time:%s\n",
        p_thread_ctl->thread_index, emp.name, emp.upd_ts);

  THREAD_FUNC_END:
    DbsDisconnThread(p_thread_ctl->thread_index);
    return;
}
